import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/home/index.vue'
import SearchView from '@/views/search/index.vue'
import DetailView from '@/views/detail/index.vue'
import IndexView from '@/views/home/home.vue'
import MyView from '@/views/home/my.vue'
import CarView from '@/views/home/car.vue'
import ClassView from '@/views/home/class.vue'
import GoodsView from '@/views/goods/index.vue'
import LoginView from '@/views/login/index.vue'
import RegisterView from '@/views/register/index.vue'
import orderView from '@/views/order/index.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 重定项
    { path: '/', redirect: '/home/index' },
    // 搜索页
    { path: '/search', component: SearchView },
    // 详情页
    { path: '/detail/:goods_id', component: DetailView },
    // 商品页
    { path: '/goods/:cat_name', component: GoodsView },
    // 登陆页
    { path: '/login', component: LoginView },
    // 注册页
    { path: '/register', component: RegisterView },
    // 订单页
    { path: '/order/:orderId', component: orderView },
    // 我的订单页面 （ 路由的懒加载 ）
    { path: '/myorder', component: () => import('@/views/myorder/index.vue') },
    // 主页
    {
      path: '/home', component: HomeView, children: [
        // 首页
        { path: 'index', component: IndexView },
        //  我的 页面
        { path: 'my', component: MyView },
        // 购物车 页面
        { path: 'car', component: CarView },
        //  分类页
        { path: 'class', component: ClassView },

      ]
    },
  ],
})
//  导航首位
router.beforeEach((to, from, next) => {
  if (to.fullPath == '/home/car' || to.fullPath == '/home/my') {
    let token = localStorage.getItem('token')
    // 进入有token页面
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 进入其他页面
    next()
  }
})
export default router
